<?php
namespace console\controllers; 
use Yii;
use common\utils\CommonFun;
use common\models\balance;
use common\models\Setting;
use common\models\Member;
use common\utils\Redis;
use common\models\WithdrawLog;
use common\models\EthTradeLog;

use xtype\Ethereum\Client;
use xtype\Ethereum\Utils;

/*
	* 以太坊交易相关定时
*/
class WithdrawController extends CoreController
{

	protected $client;

	public function actionIndex()
	{
		// return true;
		sleep(60);      
		$logPath = Yii::$app->params['logPath'];
		$lockFile = $logPath.'/withdraw.txt';
		if($time = file_exists($lockFile)){
			if((time() - $time) > 1800) unlink($lockFile);  
			return true;
		} 
		file_put_contents($lockFile,time());

		$this->client = new Client(Yii::$app->params['eth']['infuraUrl']);

		//实例化redis
   		$redis = Redis::getRedis(); 

   		$fromAddress = Yii::$app->params['eth']['address'];
   		## 检测nonce值 
		$nonce = $this->client->eth_getTransactionCount($fromAddress, 'pending');
        $nonce = Utils::hexToDec($nonce);  //十进制
   		$weNonce = $redis->hget('nonce_key','nonce');
   		if(($weNonce - $nonce)>0){
   			$redis->hset('nonce_key','nonce',$nonce);
   		}

		$data = WithdrawLog::find()->where(["state"=>'2'])->asarray()->all(); 
		if(!$data){
			unlink($lockFile);  
			return true;
		}

		$url = 'http://127.0.0.1:8080/api/eth/transferErc20';
		$usdtDecimal = Yii::$app->params['eth']['usdtDecimal'];
		$apiKey = Yii::$app->params['eth']['apiKey'];
		foreach($data as $val)
		{
			//构造交易。。。	
			$params = array(
				'privateKey'	=> Yii::$app->params['eth']['privateKey'],   //私钥
				'contractAddress'=> Yii::$app->params['eth']['usdtContractAddress'],   //合约地址  
				'toAddress'	=> trim($val['collect_info']),
				// 'GasPrice'  => $client->eth_gasPrice(),  
				'value'		=> ($val['money'] - $val['fee']) * pow(10, $usdtDecimal),             
				'nonce'		=> $redis->hget('nonce_key','nonce'),             
			); 
			$res = $this->post_curl($url,$params);        
			$res = json_decode($res,1);
			CommonFun::writeLog($res,'tixian');  
			CommonFun::writeLog('nonce:'.$params['nonce'],'tixian');
			CommonFun::writeLog('order_id:'.$val['id'],'tixian');
			if(!$res['hex']) continue;   //发送失败

			//发送交易。。。
			$sendUrl = 'https://api.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex='.$res['hex'].'&apikey='.$apiKey;
			$sendRes = $this->post_curl($sendUrl);  
			CommonFun::writeLog($sendRes,'tixian'); 
			$sendRes = json_decode($sendRes,1);
			if($sendRes['result'])
			{
				//nonce值加1 
				$nonce = $redis->hget('nonce_key','nonce');
				$redis->hset('nonce_key','nonce',$nonce+1);

				$txid = $sendRes['result'];
				$upData = array('state'=>'4', 'txid' => $txid,'update_time' => time(), 'send_nums' => $val['send_nums'] + 1); //'callback_state'=>'0','send_nums'=>$val['send_nums']+1,
				$flag1 = WithdrawLog::updateAll($upData,['id'=>$val['id']]);
				if(!$flag1) CommonFun::writeLog('状态修改失败，但转帐成功，请联系相关人员,id:'.$val['id'],'tixian');		
			}

	      	if($sendRes['error'] && strpos($sendRes['error']['message'],'nonce too low')!==false){
	        	// echo 'nonce too low --------'; 
	      		$nonce = $this->client->eth_getTransactionCount(Yii::$app->params['eth']['address'], 'pending');  
	      		$nonce = Utils::hexToDec($nonce);  //十进制    
	      		$redis->hset('nonce_key','nonce',$nonce);	
	      	}
		}
		unlink($lockFile);
	}


	/**
		* 归集

	*/
	public function actionGuiji()
	{

		sleep(60);       
		## 存储数据到redis
		$this->saveDataToRedis();     

		echo '开始时间归集：'.date("Y-m-d H:i:s").'----';
		$priKey = Yii::$app->params['eth']['guijiPrikey'];
      	$url = 'http://127.0.0.1:8080/api/eth/collection';
      	$param = array('priKey'=> $priKey);
      	$res = $this->post_curl($url,$param);    
      	echo '结束时间：'.date("Y-m-d H:i:s").'----';   
	}

	private function saveDataToRedis()
	{
		//实例化redis
   		$redis = Redis::getRedis();

      	$oldData = $redis->hgetAll('guiji_key');
      	foreach($oldData as $key=>$priKey)
      	{
         	$redis->hdel('guiji_key',$key);
      	}

		$where = ['status' => '1'];     
		$data  = EthTradeLog::find()->select(['member_id'])->where($where)->groupBy('member_id')->asarray()->all(); 

 		$Member = new Member;
		foreach($data as $val)
		{
         	$where = ["member_id" => $val['member_id']];   
         	$member = $Member::find()->select(['address','private_key'])->where($where)->asarray()->one();
			if(!$member['address']) continue;

			$privateKey = CommonFun::decrypt($member['private_key']);
			$res = $redis->hset('guiji_key',$member['address'],$privateKey); 
			if(!$res){
				var_dump($member); 
			}
		}
		return true;   
	}


	## 自动提币 检测到账
	public function actionWithdrawCheck()
	{
		echo date('Y-m-d H:i:s')."\r\n";
    	$client = new Client(Yii::$app->params['eth']['infuraUrl']);
    	$t = time() - 30*60;  
    	$data = WithdrawLog::find()
    			->where(["state"=>'4','callback_state'=>0])
    			->andWhere(['<','send_nums',3])
    			->andWhere(['<=','update_time',$t])
    			->limit(20)->asarray()->all();
    	if(!$data) return true; 

        // var_dump($data);die;

 		foreach($data as $val)
 		{
	 		$hash = $val['txid'];
			$res = $client->eth_getTransactionReceipt($hash);  

            if($res)
            {
                $status = Utils::hexToDec($res->status);
            
                if($status=='1')
                { 
                    //更新订单
                    $tmp = array('callback_state' => 1);
                }else{
                    var_dump($val['id']); 
                    $tmp = array('state'=>'2', 'callback_state'=>'0');
                }       
                               
            }else
            {
                var_dump($val['id']);
                $tmp = array('state'=>'2', 'callback_state'=>'0');  
            }
            $flag = WithdrawLog::updateAll($tmp,['id'=>$val['id']]);
 		}
	}


}